#!/usr/bin/perl

use XML::Simple;
use Data::Dumper;
use XML::TreeBuilder;
use File::Copy;

sub perform_test;

my $ARGC = $#ARGV + 1;

my $outF = "./outputs/";
my $microOutputFName = "microLir.out";
my $expectedOutputFName = "expected.out"; 
my $testCollectioName = "";

if($ARGC < 1) {
	print "Usage: $0 <test case file> [testCase]\n";
	exit(0);
}
if($ARGC >= 2) {
#$test = shift(@ARGV);
	@testCaseNames = @ARGV[1..$#ARGV];
}

my $tree = XML::TreeBuilder->new();
my $i = 0;
my $failCount = 0;
my $mainStr = "";

#system("rm err.log");	
open(FILEWRITE, "> err.log");
print FILEWRITE "";


$tree->parse_file($ARGV[0]);

print "\n";
#print $#testCaseNames+1;

if(($#testCaseNames+1) != 0) {
	foreach my $testCaseName (@testCaseNames) {
		my $testCase = $tree->find_by_attribute('name', $testCaseName);
		my $output = $testCase->attr_get_i('output');	

#	print $testCase->content_list;
		&perform_test($testCase);
	}
}
else {
	foreach my $collection ($tree->find_by_tag_name('caseCollection')) {

		my $collectionName = $collection->attr_get_i('name');
		print "\nTesting Collection: $collectionName\n";
		print "-----------------------------------\n";

		foreach my $testCase ($collection->find_by_tag_name('testCase')) {
			&perform_test($testCase);		
		}
	}
}

if($failCount == 0) {
	print "\n\n All Test Passed ! \n\n";
}
else {
	print "\n\n $failCount tests Failed ! \n\n";
}


sub perform_test {
	my $testCase = $_[0];
	my $output = $testCase->attr_get_i('output');
	open(FILEWRITE, "> $expectedOutputFName");
	print FILEWRITE $output;

	my $name = $testCase->attr_get_i('name');
	my @content = $testCase->content_list;

	my $outFilename = $outF . $name . ".ic";
	my $outLirFilename = $outF . $name . ".lir";

	my $fullTxt = $mainStr . $content[0];
	open(FILEWRITE, "> $outFilename");
	print FILEWRITE $fullTxt;

	system("../../run '$outFilename -print-lir -overwrite -L ../ic/libic.sig' 2>> err.log");
	system("java -jar microLIR.jar '$outLirFilename' > $microOutputFName");

	my $diff = `diff -b $microOutputFName $expectedOutputFName`;

	if($diff) {
		print "Test '$name' FAILED\n";
		print $diff."\n";
		$failCount++;
	}
	else {
		print "Test '$name' Passed\n";
	}
}
